package indi.mozping.buffer;

import org.junit.Test;

import java.nio.ByteBuffer;

/**
 * @author by mozping
 * @Classname BufferTest
 * @Description BufferTest
 * @Date 2019/11/27 20:39
 */

public class BufferTest {

    static final String content = "helloworld";
    static final int capacity = 128;

    @Test
    public void typeTest() {

        //分配直接内存
        ByteBuffer direct = ByteBuffer.allocateDirect(1024);
        System.out.println(direct.isDirect());

        ByteBuffer heap = ByteBuffer.allocate(1024);
        System.out.println(heap.isDirect());
    }


    @Test
    public void apiTest() {
        //1. 分配一个指定大小的缓冲区
        System.out.println("1. allocate() 创建, 容量为 " + capacity);
        ByteBuffer buf = ByteBuffer.allocate(capacity);
        printBufDetail(buf);


        //2. 利用 put() 存入数据到缓冲区中
        System.out.println("2. put() 存储 ：存入内容为：" + content);
        buf.put(content.getBytes());
        printBufDetail(buf);

        //3. 切换读取数据模式
        System.out.println("3.flip() 切换到读模式：");
        buf.flip();
        printBufDetail(buf);

        //4. 利用 get() 读取缓冲区中的数据到dst数组
        System.out.println("4. get() 读取");

        byte[] dst = new byte[buf.limit()];
        buf.get(dst);
        System.out.println("读取的内容：" + new String(dst, 0, dst.length));
        printBufDetail(buf);


        //5. rewind() : 重复读
        System.out.println("5. rewind() 可重复读");
        buf.rewind();
        printBufDetail(buf);

        //6. clear() : 清空缓冲区. 但是缓冲区中的数据依然存在，标志状态位会重置
        System.out.println("6. clear()");
        buf.clear();
        //注意这里如果get方法带有index，比如get(1)读取下标为1的内容，那么是不会影响position的，这种是绝对读取
        System.out.println("clear 后读取第一个字符： " + (char) buf.get());
        printBufDetail(buf);


        System.out.println("7.重新写入 javahelloworld ");
        buf.put("javahelloworld".getBytes());
        printBufDetail(buf);
        buf.flip();

        System.out.println("8.flip ");
        printBufDetail(buf);

        System.out.println("9.绝对读取1个，不影响position ");
        byte b = buf.get(3);
        printBufDetail(buf);

        System.out.println("10.读取批量5个 ");
        byte[] dst1 = new byte[5];
        buf.get(dst1, 0, dst1.length);
        System.out.println("读取内容：" + new String(dst1));
        printBufDetail(buf);

        System.out.println("11.mark一下,再读取5个 ");
        buf.mark();
        buf.get(dst1, 0, 5);
        System.out.println("读取内容：" + new String(dst1));
        printBufDetail(buf);

        System.out.println("12.回到mark处,重新读取5个，应该和前一次读取的是一样的 ");
        buf.reset();
        buf.get(dst1, 0, 5);
        System.out.println("读取内容：" + new String(dst1));
        printBufDetail(buf);
    }

    private static void printBufDetail(ByteBuffer buf) {
        System.out.println("Buffer 参数：position = " + buf.position() + ", limit= " + buf.limit() + ", capacity = " + buf.capacity() + "\n");
    }
}